<!-- 某个用户的所有收货地址展示 -->
<template>
  <el-card v-loading="loading" shadow="never" style="background-color: #ffffff00;">

    <!-- 添加新收货地址按钮 -->
    <el-button style="margin-bottom: 13px; width: 210px;" type="primary" round @click="addAddress">
      <template #icon>
        <el-icon>
          <font-awesome-icon :icon="['fas', 'plus']" />
        </el-icon>
      </template>
      添加新的收货地址
    </el-button>

    <el-card v-for="(item, index) in  addressData " :key="item.addressId" shadow="hover"
      style="margin-bottom: 5px; margin-top: 5px; cursor: pointer;" @click="selectAddress(item)">
      <el-row>

        <!-- 左侧小图标 -->
        <el-col :span="2" style="display: flex; align-items: center; justify-content: center;">
          <div :class="{ 'left-circle-default': item.isDefault === 1, 'left-circle': item.isDefault === 0 }">
            <el-icon style="font-size: 20px;">
              <font-awesome-icon :icon="['fas', 'location-dot']" />
            </el-icon>
          </div>
        </el-col>

        <!-- 信息展示 -->
        <el-col :span="16" :offset="1">
          <div class="name-phone">
            <span class="name">{{ item.name }}</span>
            <span class="phone-number">{{ item.phoneNumber }}</span>
            <el-tag v-if="item.isDefault === 1" class="tag" size="small" type="danger">默认</el-tag>
            <el-tag class="tag" size="small">{{ item.tag }}</el-tag>
          </div>
          <div class="addr">
            <span>{{ item.province }}</span>&emsp13;
            <span>{{ item.city }}</span>&emsp13;
            <span>{{ item.district }}</span>&emsp13;
            <span>{{ item.detail }}</span>
          </div>
        </el-col>

        <!-- 两个按钮 -->
        <el-col :span="4" :offset="1">
          <div class="right-btn">
            <el-button @click.stop="showDialog(index)" type="primary" plain round>
              <template #icon>
                <el-icon>
                  <font-awesome-icon :icon="['fas', 'pen-to-square']" />
                </el-icon>
              </template>
            </el-button>
            <el-button @click.stop="deleteAddress(index)" type="danger" plain round>
              <template #icon>
                <el-icon>
                  <font-awesome-icon :icon="['fas', 'trash-can']" />
                </el-icon>
              </template>
            </el-button>
          </div>
        </el-col>

      </el-row>
    </el-card>

  </el-card>

  <el-dialog v-model="dialogVisible1" title="新增收货地址" width="50%">
    <edit-address-card :my_address="my_address1" :newlyAdd="true" @opSuccess="opSuccess"
      ref="editAddrCardRef1"></edit-address-card>
  </el-dialog>

  <el-dialog v-model="dialogVisible2" title="编辑收货地址" width="50%">
    <edit-address-card :my_address="my_address2" :newlyAdd="false" @opSuccess="opSuccess"
      ref="editAddrCardRef2"></edit-address-card>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance } from "vue"
import { useStore } from 'vuex'
import EditAddressCard from "../components/EditAddressCard.vue"

const store = useStore();
const { proxy } = getCurrentInstance();
const loading = ref(false);
const addressData = ref([]);
const dialogVisible1 = ref(false)
const dialogVisible2 = ref(false)
const editAddrCardRef1 = ref(null);
const editAddrCardRef2 = ref(null);
const props = defineProps({  // 可以拿到父组件传入的值
  userId: "",
})
const emit = defineEmits(['changeAddress']);  // 点击卡片后调用父组件方法，切换当前订单预览选中的收货地址
const my_address1 = reactive({
  "addressId": "",
  "userId": props.userId,
  "name": "",
  "phoneNumber": "",
  "province": "",
  "city": "",
  "district": "",
  "detail": "",
  "tag": "",
  "isDefault": 0
})
const my_address2 = reactive({
  "addressId": "",
  "userId": props.userId,
  "name": "",
  "phoneNumber": "",
  "province": "",
  "city": "",
  "district": "",
  "detail": "",
  "tag": "",
  "isDefault": 0
})

/**
 * 获取当前用户的一系列地址
 */
const getAddressFromUser = async () => {
  loading.value = true;
  let ret = await proxy.$api.address.getAddressOfUser().catch(error => {
    loading.value = false;
    console.log(error);
  });
  if (ret.status === 200) {
    addressData.value = ret.data;
  }
  loading.value = false;
}

/**
 * 拷贝数据并显示模态框
 */
const showDialog = (index) => {
  my_address2.addressId = addressData.value[index].addressId;
  my_address2.name = addressData.value[index].name;
  my_address2.phoneNumber = addressData.value[index].phoneNumber;
  my_address2.province = addressData.value[index].province;
  my_address2.city = addressData.value[index].city;
  my_address2.district = addressData.value[index].district;
  my_address2.detail = addressData.value[index].detail;
  my_address2.tag = addressData.value[index].tag;
  my_address2.isDefault = addressData.value[index].isDefault;
  dialogVisible2.value = true;

  // 清空一下检验的爆红
  if (editAddrCardRef2.value)
    editAddrCardRef2.value.clearValidAndSelOps();
  else
    console.log('editAddrCardRef2.value 还是 null')
}

/**
 * 清空数据并显示模态框
 */
const addAddress = () => {
  my_address1.addressId = "";
  my_address1.name = "";
  my_address1.phoneNumber = "";
  my_address1.province = "";
  my_address1.city = "";
  my_address1.district = "";
  my_address1.detail = "";
  my_address1.tag = "";
  my_address1.isDefault = 0;
  dialogVisible1.value = true;

  // 先清空一下检验的爆红
  if (editAddrCardRef1.value)
    editAddrCardRef1.value.clearValidAndSelOps();
  else
    console.log('editAddrCardRef1.value 还是 null')
}

/**
 * 删除指定的收货地址
 */
const deleteAddress = async (index) => {
  if (addressData.value[index].addressId === store.state.address.addressId) {
    // 避免订单预览选中地址，又把这个地址给删除了的尴尬情况
    ElMessageBox.alert("当前订单预览选中该收货地址，请先为订单预览选择另一个收货地址后，再尝试删除该收货地址。", "提示")
  } else {
    let ret = await ElMessageBox.confirm(
      '删除后将无法恢复，确定删除该收货地址吗？',
      '确认删除',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      });
    if (ret === 'confirm') {
      loading.value = true;
      let res = await proxy.$api.address.deleteAddress(addressData.value[index].addressId).catch(error => {
        console.log(error);
        loading.value = false;
      });
      if (res.status === 200) {
        ElMessage.success({ showClose: true, message: "成功删除收货地址" });
        await getAddressFromUser();
      }
      loading.value = false;
    }
  }
}

/**
 * 子组件EditAddressCard成功添加/编辑地址后调用，重新获取一遍地址列表
 */
const opSuccess = async () => {
  dialogVisible1.value = false;
  dialogVisible2.value = false;
  await getAddressFromUser();
}

/**
 * 修改 store.state.address.addressId 更改存储的当前订单预览中选择的收货地址ID
 */
const selectAddress = (address) => {
  console.log('selectAddress被调用');
  store.commit('address/updateAddressId', address.addressId);
  emit('changeAddress');
}

onMounted(async () => {
  await getAddressFromUser();
})
</script>


<style lang="less" scoped>
.left-circle {
  height: 50px;
  width: 50px;
  border-radius: 25px;
  background: linear-gradient(to top, #cfd9df 0%, #e2ebf0 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 1px 2px 2px rgba(60, 59, 56, 0.329);
}

.left-circle-default {
  height: 50px;
  width: 50px;
  border-radius: 25px;
  background: linear-gradient(to top, #efbd9b 0%, #fcb5a2 100%);
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 1px 2px 2px rgba(60, 59, 56, 0.329);
}

.name-phone {
  display: flex;
  align-items: center;

  .name {
    font-size: 16px;
    font-weight: 600;
  }

  .phone-number {
    font-size: 15px;
    margin-left: 10px;
  }

  .tag {
    margin-left: 10px;
  }
}


.addr {
  margin-top: 15px;
  font-size: 15px;
  color: rgb(147, 150, 152);
  line-height: 23px;
}

.right-btn {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>